package com.ucar.training.controller;

import com.ucar.training.common.ResponseEnum;
import com.ucar.training.common.Result;
import com.ucar.training.domain.User;
import com.ucar.training.service.IUserService;
import com.ucar.training.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author XiongMM
 * @date 2019/7/29 11:16
 * @description
 */
public class RegisterServlet extends HttpServlet{

    private IUserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = new User();
        //将客户端提交的表单数据封装到RegisterFormBean对象中
        String userName = request.getParameter("userName");
        user.setUserName(userName);
        String trueName = request.getParameter("trueName");
        user.setTrueName(trueName);
        String sex = request.getParameter("sex");
        user.setSex(Integer.parseInt(sex));
        String age = request.getParameter("age");
        user.setAge(Integer.parseInt(age));
        String password = request.getParameter("password");
        user.setPassword(password);
        String phone = request.getParameter("phone");
        user.setPhone(phone);
        String email = request.getParameter("email");
        user.setEmail(email);
        String[] hobbys = request.getParameterValues("hobby");
        user.setHobbys(hobbys);
        String signature = request.getParameter("signature");
        user.setSignature(signature);
        Result result = userService.registerUser(user);
        if(result.getCode().name().equals(ResponseEnum.SUCCESS.name())){
            String message = String.format(
                    "注册成功！！3秒后为您自动跳到登录页面！！<meta http-equiv='refresh' content='3;url=%s'/>",
                    request.getContextPath() + "/final/uilogin");
            request.setAttribute("message", message);
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        }else{
            String message = String.format(
                    "注册失败！！失败原因：【%s】 ，3秒后为您自动跳到登录页面！！<meta http-equiv='refresh' content='3;url=%s'/>",
                    result.getMsg(),request.getContextPath() + "/final/uiregister");
            request.setAttribute("message", message);
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        }
    }
}
